require(['jquery', 'echarts', 'dataTool', 'socket.io',], function ($, echarts) {
    var color_pool = ['#2980B9', '#E74C3C', '#48C9B0', '#F7DC6F', '#B9770E', '#8E44AD', '#797D7F', '#7B241C', '#EC7063', '#884EA0',
        '#AF7AC5', '#5DADE2', '#1ABC9C', '#27AE60', '#F39C12', '#EDBB99', '#F5B7B1', '#FAD7A0']
    const io = require('socket.io');
    var origin_net, net, task_id;
    var edges = [], labels = [];
    var categories = [], legend = [];
    var pca_data = []

    const socket = io('/status', {});
    var classification_chart = echarts.init(document.getElementById("classification"));
    var pca_chart = echarts.init(document.getElementById("pca"));
    var kmeans_chart = echarts.init(document.getElementById("kmeans"));

    function apiFn() {
        this.hostname = ""
    }

    function countTrianglesPerNode(data) {
        return "not implemented"
        var adjacencyMatrix = createAdjacencyMatrix(data);
        var triangleCounts = []; // 存储每个节点参与的三角形数量  

        for (var i = 0; i < adjacencyMatrix.length; i++) {
            var nodeTriangles = 0;
            for (var j = i + 1; j < adjacencyMatrix.length; j++) {
                if (adjacencyMatrix[i][j] === 1) { // 节点i和j相连  
                    var commonNeighbors = adjacencyMatrix[i].filter(function (val, index) {
                        return val === 1 && index !== i && index !== j && adjacencyMatrix[j][index] === 1;
                    }).length;
                    nodeTriangles += commonNeighbors;
                }
            }
            triangleCounts.push(nodeTriangles);
        }

        // 计算平均三角形个数  
        var averageTriangleCount = triangleCounts.reduce((sum, val) => sum + val, 0) / triangleCounts.length;
        return averageTriangleCount;
    }

    function createAdjacencyMatrix(data) {//平均聚集系数
        return "not implemented"
        var nodeCount = data.nodes.length;
        var adjacencyMatrix = Array(nodeCount).fill(0).map(() => Array(nodeCount).fill(0));
        data.edges.forEach(edge => {
            adjacencyMatrix[edge.source][edge.target] = 1;
            adjacencyMatrix[edge.target][edge.source] = 1; // 对于无向图  
        });
        return adjacencyMatrix;
    }

    function calculateDensity(data) {
        var nodeCount = data.nodes.length;
        var maxEdges = nodeCount * (nodeCount - 1) / 2; // 最大可能边数  
        var actualEdges = data.edges.length; // 实际边数  
        return actualEdges / maxEdges;
    }

    function calculateAverageClusteringCoefficient(data) {//平均三角形个数
        return "not implemented"
    }

    function countTriangles(data) {//三角形个数
        return "not implemented"
        var adjacencyMatrix = createAdjacencyMatrix(data);
        var triangleCount = 0;

        for (var i = 0; i < adjacencyMatrix.length; i++) {
            for (var j = i + 1; j < adjacencyMatrix.length; j++) {
                if (adjacencyMatrix[i][j] === 1) { // 节点i和j相连  
                    var commonNeighbors = adjacencyMatrix[i].filter(function (val, index) {
                        return val === 1 && index !== i && index !== j && adjacencyMatrix[j][index] === 1;
                    }).length;
                    triangleCount += commonNeighbors;
                }
            }
        }

        return triangleCount / 3; // 每个三角形被计算了三次，所以需要除以3  
    }

    function calculateDegreeStatistics(data) {
        // 创建一个对象来存储每个节点的度数  
        var degrees = {};

        // 遍历所有边来计算度数  
        data.edges.forEach(function (edge) {
            var source = edge.source;
            var target = edge.target;

            // 如果节点不在degrees对象中，则初始化为0  
            if (!degrees.hasOwnProperty(source)) {
                degrees[source] = 0;
            }
            if (!degrees.hasOwnProperty(target)) {
                degrees[target] = 0;
            }

            // 增加源节点和目标节点的度数  
            degrees[source]++;
            degrees[target]++;
        });

        // 计算最大、最小和平均度数  
        var maxDegree = 0;
        var minDegree = Infinity;
        var sumDegree = 0;
        var nodeCount = 0;

        for (var nodeName in degrees) {
            var degree = degrees[nodeName];
            maxDegree = Math.max(maxDegree, degree);
            minDegree = Math.min(minDegree, degree);
            sumDegree += degree;
            nodeCount++;
        }

        var averageDegree = sumDegree / nodeCount;

        // 返回统计结果  
        return {
            maxDegree: maxDegree,
            minDegree: minDegree,
            averageDegree: averageDegree
        };
    }

    apiFn.prototype = {
        Init: function () {
            socket.on('embed_log', function (res) {
                $("#algoRes").append(res + '<br/>');
                if (res.indexOf("Run classification") >= 0) {
                    classification_chart.resize();
                    classification_chart.showLoading();
                }
                if (res.indexOf("Run PCA") >= 0) {
                    pca_chart.resize();
                    pca_chart.showLoading();
                }
                if (res.indexOf("PCA done") >= 0) {
                    console.log(pca_data)
                    pca_chart.hideLoading();
                }
                if (res.indexOf("Run K-Means") >= 0) {
                    var option = {
                        color: color_pool,
                        xAxis: {
                            show: false,
                            type: 'value'
                        },
                        yAxis: {
                            show: false
                        },
                        series: [
                            {
                                type: 'scatter',
                                name: 'pca',
                                data: pca_data,
                                itemStyle: {
                                    color: function (params) {
                                        return color_pool[labels[params.dataIndex][1]];
                                    }
                                }
                            }
                        ]
                    };
                    pca_chart.setOption(option);
                    kmeans_chart.resize();
                    kmeans_chart.showLoading();
                }
            });
            socket.on('classification', function (data) {
                classification_chart.hideLoading();
                var option = {
                    textStyle: {
                        color: 'white'
                    },
                    legend: {
                        data: ['Micro-F1', 'Macro-F1'],
                        textStyle: {
                            color: 'white'
                        }
                    },
                    xAxis: {
                        type: 'value',
                        axisLine: {
                            lineStyle: {
                                color: 'white'
                            }
                        },
                        axisTick: {
                            lineStyle: {
                                color: 'white'
                            }
                        },
                    },
                    yAxis: {
                        axisLine: {
                            lineStyle: {
                                color: 'white'
                            }
                        },
                        axisTick: {
                            lineStyle: {
                                color: 'white'
                            }
                        },
                        type: 'value',
                        min: data['f1-macro'][0][1] - 0.1 >= 0 ? data['f1-macro'][0][1] - 0.1 : 0,
                        max: data['f1-micro'][8][1] + 0.1 <= 1 ? data['f1-micro'][8][1] + 0.1 : 1,
                    },
                    series: [
                        {
                            name: 'Micro-F1',
                            type: 'line',
                            data: data['f1-micro']
                        },
                        {
                            name: 'Macro-F1',
                            type: 'line',
                            data: data['f1-macro']
                        },
                    ]
                };
                classification_chart.setOption(option);
            });
            socket.on('pca', function (data) {
                pca_data = JSON.parse(JSON.stringify(data))
            });
            socket.on('k-means', function (data) {
                net = JSON.parse(JSON.stringify(origin_net));
                kmeans_chart.hideLoading();
                for (var i = 0; i < net.nodes.length; i++) {
                    net.nodes[i].category = data[net.nodes[i].name];
                }
                var option = {
                    tooltip: {},
                    color: color_pool,
                    legend: {
                        data: legend,
                        textStyle: {
                            color: 'white'
                        }
                    },
                    series: [{
                        type: 'graph',
                        layout: 'force',
                        symbolSize: 12,
                        roam: true,
                        force: { //力引导图基本配置
                            repulsion: 100,//节点之间的斥力因子。支持数组表达斥力范围，值越大斥力越大。
                            gravity: 0.03,//节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
                            edgeLength: 150,//边的两个节点之间的距离，这个距离也会受 repulsion。[10, 50] 。值越小则长度越长
                            layoutAnimation: false
                            //因为力引导布局会在多次迭代后才会稳定，这个参数决定是否显示布局的迭代动画，在浏览器端节点数据较多（>100）的时候不建议关闭，布局过程会造成浏览器假死。
                        },
                        // edgeSymbol: ['circle', 'arrow'],
                        data: net.nodes,
                        links: net.edges,
                        categories: categories,
                        label: {
                            normal: {
                                show: false,
                                textStyle: {
                                    fontSize: 10
                                },
                            }
                        },
                        edgeLabel: {
                            show: true,
                            normal: {
                                textStyle: {
                                    fontSize: 20
                                }
                            }
                        },
                        normal: {
                            width: 0.3,
                            curveness: 0.3,
                            opacity: 0.7
                        }
                    }]
                };
                kmeans_chart.setOption(option);
            });
            this.departmentFn();
            this.policyFn();
            this.contentFn();
            this.publicNumFn();
            setInterval(function () {
                numInit()
            }, 6000);
        },
        // 算法运行时间
        departmentFn: function () {
            var dataArr = [
                {name: '算法运行时间：', value: 300},
            ];
            // 中间滚动数据展示
            for (var j = 0; j < dataArr.length; j++) {
                // $(".main_list_title").text(dataArr[j].name)
            }
        },
        // 算法运行结果
        policyFn: function () {
            // $(".main_bottom_t_l_main2").jCarouselLite({
            //     vertical: true,
            //     hoverPause: true,
            //     visible: 4,
            //     auto: 1000,
            //     speed: 500
            // });
        },
        // 初始化网络可视化
        contentFn: function () {
            var network1 = $('#contentId');
            myChart = echarts.init(network1.get(0));
            myChart.showLoading();
            //原始网络
            $("#choose_dataset1").on('click', function (e) {
                $.ajax({
                    url: '/networkapi/dataset',
                    type: 'get',
                    data: {
                        dataset: e.target.id
                    },
                    success: function (graph) {
                        console.log(graph);
                        console.log(e.target.id);
                        net = JSON.parse(JSON.stringify(graph));
                        origin_net = JSON.parse(JSON.stringify(graph));
                        myChart.hideLoading();
                        labels = graph['label'];
                        edges = [];
                        console.log(labels);
                        for (var i = 0; i < graph.nodes.length; i++) {
                            for (var k = 0; k < graph.nodes.length; k++) {
                                if (labels[k][0] == graph.nodes[i].name) {
                                    graph.nodes[i].category = labels[k][1];
                                    break;
                                }
                            }

                            graph.nodes[i].name = graph.nodes[i].name.toString();
                        }
                        for (var j = 0; j < graph.edges.length; j++) {
                            edges.push([graph.edges[j].source, graph.edges[j].target, 0, 0]);
                            graph.edges[j].source = graph.edges[j].source.toString();
                            graph.edges[j].target = graph.edges[j].target.toString();
                        }
                        categories = [];
                        legend = [];
                        if (e.target.id == 'dblp') {
                            categories[0] = {name: 'author'};
                            categories[1] = {name: 'paper'};
                            categories[2] = {name: 'conference'};
                            legend[0] = {name: 'author'};
                            legend[1] = {name: 'paper'};
                            legend[2] = {name: 'conference'};


                        } else if (e.target.id == 'review-graph') {
                            categories[0] = {name: 'reviewer'};
                            categories[1] = {name: 'movie'};

                            legend[0] = {name: 'reviewer'};
                            legend[1] = {name: 'movie'};

                        } else if (e.target.id == 'upaper') {
                            categories[0] = {name: 'paper'};
                            categories[1] = {name: 'tutor'};
                            categories[2] = {name: 'academy'};
                            legend[0] = {name: 'paper'};
                            legend[1] = {name: 'tutor'};
                            legend[2] = {name: 'academy'};

                        }
                        //for (var i = 0; i < graph.classes; i++) {
                        //    categories[i] = {
                        //        name: '类别' + (i + 1)
                        //    };
                        //    legend[i] = {
                        //        name: '类别' + (i + 1)
                        //    };
                        //}
                        $("#dataset_title").html(e.target.id);
                        $("#jiedianshu").html(net.nodes.length);
                        $("#bianshu").html(net.edges.length);
                        var statistics = calculateDegreeStatistics(net);
                        $("#zuidadu").html(statistics.maxDegree);
                        $("#zuixiaodu").html(statistics.minDegree);
                        $("#pingjundu").html((Math.round(statistics.averageDegree * 1000) / 1000));
                        $("#wangluomidu").html(Math.round(calculateDensity(net) * 1000) / 1000)
                        // $("#juleixishu").html(calculateAverageClusteringCoefficient(net))
                        // $("#sanjiaoxinggeshu").html(countTriangles(net))
                        // $("#pingjunsanjiaoxinggeshu").html(countTrianglesPerNode(net))
                        option = {
                            tooltip: {},
                            color: color_pool,
                            legend: {
                                data: legend,
                                textStyle: {
                                    color: 'white'
                                }
                            },
                            series: [{
                                type: 'graph',
                                layout: 'force',
                                //symbolSize: 12,
                                roam: true,
                                force: { //力引导图基本配置
                                    repulsion: 100,//节点之间的斥力因子。支持数组表达斥力范围，值越大斥力越大。
                                    //gravity: 0.03,//节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
                                    //edgeLength: 150,//边的两个节点之间的距离，这个距离也会受 repulsion。[10, 50] 。值越小则长度越长
                                    //layoutAnimation: false
                                    //因为力引导布局会在多次迭代后才会稳定，这个参数决定是否显示布局的迭代动画，在浏览器端节点数据较多（>100）的时候不建议关闭，布局过程会造成浏览器假死。
                                },
                                edgeSymbol: ['none', 'none'],
                                data: graph.nodes,
                                links: graph.edges,
                                categories: categories,
                                label: {
                                    normal: {
                                        show: false,
                                        textStyle: {
                                            fontSize: 10
                                        },
                                    }
                                },
                                // itemStyle: {
                                //     color: '#FD9133'
                                // },
                                edgeLabel: {
                                    show: true,
                                    normal: {
                                        textStyle: {
                                            fontSize: 20
                                        }
                                    }
                                },
                                normal: {
                                    width: 0.3,
                                    curveness: 0.3,
                                    opacity: 0.7
                                }
                            }]
                        };


                        myChart.setOption(option);
                    }
                });
            })
            $("#choose_dataset").on('click', function (e) {
                if (e.target.id == "beifanggongyedaxue") {
                    $.ajax({
                        url: '/static/data/complex/beifanggongyedaxue.json', success: function (graph) {
                            net = JSON.parse(JSON.stringify(graph));
                            origin_net = JSON.parse(JSON.stringify(graph));
                            console.log(net)
                            myChart.hideLoading();
                            // labels = graph['label'];
                            edges = [];
                            for (var i = 0; i < graph.nodes.length; i++) {
                                // graph.nodes[i].category = labels[graph.nodes[i].name][1];
                                graph.nodes[i].name = graph.nodes[i].name.toString();
                            }
                            for (var j = 0; j < graph.edges.length; j++) {
                                edges.push([graph.edges[j].source, graph.edges[j].target, 0, 0]);
                                graph.edges[j].source = graph.edges[j].source.toString();
                                graph.edges[j].target = graph.edges[j].target.toString();
                            }
                            categories = [];
                            legend = [];
                            for (var i = 0; i < graph.classes; i++) {
                                categories[i] = {
                                    name: '类别' + (i + 1)
                                };
                                legend[i] = {
                                    name: '类别' + (i + 1)
                                };
                            }
                            $("#dataset_title").html(e.target.id);
                            $("#jiedianshu").html(net.nodes.length);
                            $("#bianshu").html(net.edges.length);
                            var statistics = calculateDegreeStatistics(net);
                            $("#zuidadu").html(statistics.maxDegree);
                            $("#zuixiaodu").html(statistics.minDegree);
                            $("#pingjundu").html((Math.round(statistics.averageDegree * 1000) / 1000));
                            $("#wangluomidu").html(Math.round(calculateDensity(net) * 1000) / 1000)
                            // $("#juleixishu").html(calculateAverageClusteringCoefficient(net))
                            // $("#sanjiaoxinggeshu").html(countTriangles(net))
                            // $("#pingjunsanjiaoxinggeshu").html(countTrianglesPerNode(net))
                            option = {
                                tooltip: {},
                                color: color_pool,
                                legend: {
                                    data: legend,
                                    textStyle: {
                                        color: 'white'
                                    }
                                },
                                series: [{
                                    type: 'graph',
                                    layout: 'force',
                                    symbolSize: 12,
                                    roam: true,
                                    force: { //力引导图基本配置
                                        repulsion: 100,//节点之间的斥力因子。支持数组表达斥力范围，值越大斥力越大。
                                        gravity: 0.03,//节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
                                        edgeLength: 150,//边的两个节点之间的距离，这个距离也会受 repulsion。[10, 50] 。值越小则长度越长
                                        layoutAnimation: false
                                        //因为力引导布局会在多次迭代后才会稳定，这个参数决定是否显示布局的迭代动画，在浏览器端节点数据较多（>100）的时候不建议关闭，布局过程会造成浏览器假死。
                                    },
                                    edgeSymbol: ['circle', 'arrow'],
                                    // data: graph.nodes.slice(1,200),
                                    // links: graph.edges.slice(1,400),
                                    data: graph.nodes,
                                    links: graph.edges,
                                    categories: categories,
                                    label: {
                                        normal: {
                                            show: false,
                                            textStyle: {
                                                fontSize: 10
                                            },
                                        }
                                    },
                                    // itemStyle: {
                                    //     color: '#FD9133'
                                    // },
                                    edgeLabel: {
                                        show: true,
                                        normal: {
                                            textStyle: {
                                                fontSize: 20
                                            }
                                        }
                                    },
                                    normal: {
                                        width: 0.3,
                                        curveness: 0.3,
                                        opacity: 0.7
                                    }
                                }]
                            };
                            myChart.setOption(option);
                        }
                    });
                }
                if (e.target.id == "mouzuzhi") {
                    let datastr = e.target.id
                    $.get('/static/data/complex/complex-network.json', function (graph) {
                        net = JSON.parse(JSON.stringify(graph));
                        origin_net = JSON.parse(JSON.stringify(graph));
                        myChart.hideLoading();
                        // labels = graph['label'];
                        edges = [];
                        for (var i = 0; i < graph.nodes.length; i++) {
                            // graph.nodes[i].category = labels[graph.nodes[i].name][1];
                            graph.nodes[i].name = graph.nodes[i].name.toString();
                        }
                        for (var j = 0; j < graph.edges.length; j++) {
                            edges.push([graph.edges[j].source, graph.edges[j].target, 0, 0]);
                            graph.edges[j].source = graph.edges[j].source.toString();
                            graph.edges[j].target = graph.edges[j].target.toString();
                        }
                        categories = [];
                        legend = [];
                        for (var i = 0; i < graph.classes; i++) {
                            categories[i] = {
                                name: '类别' + (i + 1)
                            };
                            legend[i] = {
                                name: '类别' + (i + 1)
                            };
                        }
                        $("#dataset_title").html(e.target.id);
                        $("#jiedianshu").html(net.nodes.length);
                        $("#bianshu").html(net.edges.length);
                        var statistics = calculateDegreeStatistics(net);
                        $("#zuidadu").html(statistics.maxDegree);
                        $("#zuixiaodu").html(statistics.minDegree);
                        $("#pingjundu").html((Math.round(statistics.averageDegree * 1000) / 1000));
                        $("#wangluomidu").html(Math.round(calculateDensity(net) * 1000) / 1000)
                        // $("#juleixishu").html(calculateAverageClusteringCoefficient(net))
                        // $("#sanjiaoxinggeshu").html(countTriangles(net))
                        // $("#pingjunsanjiaoxinggeshu").html(countTrianglesPerNode(net))
                        option = {
                            tooltip: {},
                            color: color_pool,
                            legend: {
                                data: legend,
                                textStyle: {
                                    color: 'white'
                                }
                            },
                            series: [{
                                type: 'graph',
                                layout: 'force',
                                symbolSize: 12,
                                roam: true,
                                force: { //力引导图基本配置
                                    repulsion: 100,//节点之间的斥力因子。支持数组表达斥力范围，值越大斥力越大。
                                    gravity: 0.03,//节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
                                    edgeLength: 150,//边的两个节点之间的距离，这个距离也会受 repulsion。[10, 50] 。值越小则长度越长
                                    layoutAnimation: false
                                    //因为力引导布局会在多次迭代后才会稳定，这个参数决定是否显示布局的迭代动画，在浏览器端节点数据较多（>100）的时候不建议关闭，布局过程会造成浏览器假死。
                                },
                                edgeSymbol: ['circle', 'arrow'],
                                data: graph.nodes,
                                links: graph.edges,
                                categories: categories,
                                label: {
                                    normal: {
                                        show: false,
                                        textStyle: {
                                            fontSize: 10
                                        },
                                    }
                                },
                                // itemStyle: {
                                //     color: '#FD9133'
                                // },
                                edgeLabel: {
                                    show: true,
                                    normal: {
                                        textStyle: {
                                            fontSize: 20
                                        }
                                    }
                                },
                                normal: {
                                    width: 0.3,
                                    curveness: 0.3,
                                    opacity: 0.7
                                }
                            }]
                        };
                        myChart.setOption(option);
                    })
                } else {
                    $.ajax({
                        url: '/networkapi/dataset',
                        type: 'get',
                        data: {
                            dataset: e.target.id
                        },
                        success: function (graph) {
                            net = JSON.parse(JSON.stringify(graph));
                            origin_net = JSON.parse(JSON.stringify(graph));
                            myChart.hideLoading();
                            labels = graph['label'];
                            edges = [];
                            for (var i = 0; i < graph.nodes.length; i++) {
                                graph.nodes[i].category = labels[graph.nodes[i].name][1];
                                graph.nodes[i].name = graph.nodes[i].name.toString();
                            }
                            for (var j = 0; j < graph.edges.length; j++) {
                                edges.push([graph.edges[j].source, graph.edges[j].target, 0, 0]);
                                graph.edges[j].source = graph.edges[j].source.toString();
                                graph.edges[j].target = graph.edges[j].target.toString();
                            }
                            categories = [];
                            legend = [];
                            switch (e.target.id) {
                                case 'xbrazil-flights': {
                                    let leibie = ["航班1", "航班2", "航班3", "航班4",]
                                    for (var i = 0; i < graph.classes; i++) {
                                        categories[i] = {
                                            name: leibie[i]
                                        };
                                        legend[i] = {
                                            name: leibie[i]
                                        };
                                    }
                                    break;
                                }
                                case 'xbarbell': {
                                    let leibie = ["杠铃节点1", "杠铃节点2", "杠铃节点3", "杠铃节点4", "杠铃节点5", "杠铃节点6", "杠铃节点7"]
                                    for (var i = 0; i < graph.classes; i++) {
                                        categories[i] = {
                                            name: leibie[i]
                                        };
                                        legend[i] = {
                                            name: leibie[i]
                                        };
                                    }
                                    break;
                                }
                                case 'xeurope-flights': {
                                    let leibie = ["航班1", "航班2", "航班3", "航班4",]
                                    for (var i = 0; i < graph.classes; i++) {
                                        categories[i] = {
                                            name: leibie[i]
                                        };
                                        legend[i] = {
                                            name: leibie[i]
                                        };
                                    }
                                    break;
                                }
                                case 'xhospital': {
                                    let leibie = ["医生", "护士", "病人", "护工",]
                                    for (var i = 0; i < graph.classes; i++) {
                                        categories[i] = {
                                            name: leibie[i]
                                        };
                                        legend[i] = {
                                            name: leibie[i]
                                        };
                                    }
                                    break;
                                }
                                default: {
                                    for (var i = 0; i < graph.classes; i++) {
                                        categories[i] = {
                                            name: '类别' + (i + 1)
                                        };
                                        legend[i] = {
                                            name: '类别' + (i + 1)
                                        };
                                    }
                                }
                            }
                            $("#dataset_title").html(e.target.id);
                            $("#jiedianshu").html(net.nodes.length);
                            $("#bianshu").html(net.edges.length);
                            var statistics = calculateDegreeStatistics(net);
                            $("#zuidadu").html(statistics.maxDegree);
                            $("#zuixiaodu").html(statistics.minDegree);
                            $("#pingjundu").html((Math.round(statistics.averageDegree * 1000) / 1000));
                            $("#wangluomidu").html(Math.round(calculateDensity(net) * 1000) / 1000)
                            // $("#juleixishu").html(calculateAverageClusteringCoefficient(net))
                            // $("#sanjiaoxinggeshu").html(countTriangles(net))
                            // $("#pingjunsanjiaoxinggeshu").html(countTrianglesPerNode(net))
                            option = {
                                tooltip: {},
                                color: color_pool,
                                legend: {
                                    data: legend,
                                    orient: 'horizontal',
                                    x:'center',
                                    y:'bottom',
                                    textStyle: {
                                        color: 'white'
                                    }
                                },
                                series: [{
                                    type: 'graph',
                                    layout: 'force',
                                    symbolSize: 12,
                                    roam: true,
                                    force: { //力引导图基本配置
                                        repulsion: 100,//节点之间的斥力因子。支持数组表达斥力范围，值越大斥力越大。
                                        gravity: 0.03,//节点受到的向中心的引力因子。该值越大节点越往中心点靠拢。
                                        edgeLength: 150,//边的两个节点之间的距离，这个距离也会受 repulsion。[10, 50] 。值越小则长度越长
                                        layoutAnimation: false
                                        //因为力引导布局会在多次迭代后才会稳定，这个参数决定是否显示布局的迭代动画，在浏览器端节点数据较多（>100）的时候不建议关闭，布局过程会造成浏览器假死。
                                    },
                                    edgeSymbol: ['circle', 'arrow'],
                                    data: graph.nodes,
                                    links: graph.edges,
                                    categories: categories,
                                    label: {
                                        normal: {
                                            show: false,
                                            textStyle: {
                                                fontSize: 10
                                            },
                                        }
                                    },
                                    // itemStyle: {
                                    //     color: '#FD9133'
                                    // },
                                    edgeLabel: {
                                        show: true,
                                        normal: {
                                            textStyle: {
                                                fontSize: 20
                                            }
                                        }
                                    },
                                    normal: {
                                        width: 0.3,
                                        curveness: 0.3,
                                        opacity: 0.7
                                    }
                                }]
                            };
                            myChart.setOption(option);
                        }
                    });
                }
            });
            // $("#brazil-flights").trigger('click');
            $("#barbell").trigger('click');
        },
        // 网络算法可视化
        publicNumFn: function () {

            //zyn:计算基本属性
            $("#nkit_getBasicAttribute").on('click', function () {
                progressBarToZero();
                console.log('getBasicAttribute');
                var dataArray = [];
                for (var j = 0; j < net.edges.length; j++) {
                    dataArray[j] = new Array(4);
                    for (var k = 0; k < 2; k++) {
                        if (k === 0) {
                            dataArray[j][k] = parseInt(net.edges[j].source)
                        } else
                            dataArray[j][k] = parseInt(net.edges[j].target)
                    }
                    dataArray[j][2] = dataArray[j][3] = 1;//边的另外两个属性，暂时搁置
                }
                let num_nodes = net.nodes.length;
                $.ajax({
                    type: "POST",
                    url: "/networkitapi/getBasicAttribute",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({//发送到服务器的数据
                        data: dataArray,
                        num_nodes: num_nodes
                    }),
                    dataType: "JSON",
                    success: function (data) {
                        progressBar();
                        $("#algoRes").empty();
                        $("#algoRes").append('网络基本属性');
                        $("#algoRes").append("<br/>");
                        Object.keys(data).forEach(function (key) {
                            $("#algoRes").append(key + ':' + data[key]);
                            $("#algoRes").append("<br/>");
                            $("#juleixishu").html(Math.round(data["去除自环后_聚类系数"] * 1000) / 1000)
                            $("#zihuanshu").html(data["自环数"])
                            $("#duxiangsixing").html(Math.round(data["度相似性"] * 1000) / 1000)
                        });
                    }
                });
            });

            $("#nkit_getConnectedComponents").on('click', function () {
                progressBarToZero();
                console.log('nkit_getConnectedComponents');
                var dataArray = [];
                for (var j = 0; j < net.edges.length; j++) {
                    dataArray[j] = new Array(4);
                    for (var k = 0; k < 2; k++) {
                        if (k === 0) {
                            dataArray[j][k] = parseInt(net.edges[j].source)
                        } else
                            dataArray[j][k] = parseInt(net.edges[j].target)
                    }
                    dataArray[j][2] = dataArray[j][3] = 1;//边的另外两个属性，暂时搁置
                }
                let num_nodes = net.nodes.length;
                $.ajax({
                    type: "POST",
                    url: "/networkitapi/getConnectedComponents",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({//发送到服务器的数据
                        data: dataArray,
                        num_nodes: num_nodes
                    }),
                    dataType: "JSON",
                    success: function (data) {
                        progressBar();
                        $("#algoRes").empty();

                        console.log(data)
                        net = JSON.parse(JSON.stringify(origin_net));
                        var vector_ = $('#vector');

                        myChart3 = echarts.init(vector_.get(0));
                        myChart3.clear();
                        myChart3.showLoading();
                        myChart3.hideLoading();
                        var cnt = 0;
                        for (i = 0, len = data["Components"].length; j < len; i++) {
                            // console.log(item)
                            if (item.length < 5) {
                                continue;
                            }
                            ;
                            cnt++;
                            data["Components"][i].foreach(function (item) {
                                net.nodes.forEach(node => {
                                    if (item == node.name) {
                                        node.category = parseInt(key);
                                    }
                                })
                            })
                        }
                        var categories = [];
                        var legend = [];
                        for (var i = 0; i < cnt; i++) {
                            categories[i] = {
                                name: '子图' + (i + 1)
                            };
                            legend[i] = {
                                name: '子图' + (i + 1)
                            };
                        }
                        option = {
                            tooltip: {},
                            legend: {
                                data: legend,
                                textStyle: {
                                    color: 'white'
                                }
                            },
                            series: [{
                                type: 'graph',
                                layout: 'force',
                                roam: true,
                                force: {
                                    repulsion: 150,
                                    edgeLength: 200,
                                    layoutAnimation: false
                                },
                                edgeSymbol: ['', 'arrow'],
                                categories: categories,
                                data: net.nodes,
                                links: net.edges,
                                label: {
                                    normal: {
                                        show: false,
                                        textStyle: {
                                            fontSize: 10
                                        },
                                    }
                                },
                                edgeLabel: {
                                    show: true,
                                    normal: {
                                        textStyle: {
                                            fontSize: 20
                                        }
                                    }
                                },
                                normal: {
                                    width: 0.3,
                                    curveness: 0.3,
                                    opacity: 0.7
                                }
                            }]
                        };
                        myChart3.setOption(option);
                        $("#algoRes").append('连通子图');
                        $("#algoRes").append("<br/>");
                        $("#algoRes").append("ComponetSize:");
                        $("#algoRes").append((JSON.stringify(data["ComponentSizes"])));
                    }
                });
            });


            $("#nkit_getBiConnectedComponents").on('click', function () {
                progressBarToZero();
                console.log('nkit_getBiConnectedComponents');
                var dataArray = [];
                for (var j = 0; j < net.edges.length; j++) {
                    dataArray[j] = new Array(4);
                    for (var k = 0; k < 2; k++) {
                        if (k === 0) {
                            dataArray[j][k] = parseInt(net.edges[j].source)
                        } else
                            dataArray[j][k] = parseInt(net.edges[j].target)
                    }
                    dataArray[j][2] = dataArray[j][3] = 1;//边的另外两个属性，暂时搁置
                }
                let num_nodes = net.nodes.length;
                $.ajax({
                    type: "POST",
                    url: "/networkitapi/getBiconnectedComponents",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({//发送到服务器的数据
                        data: dataArray,
                        num_nodes: num_nodes
                    }),
                    dataType: "JSON",
                    success: function (data) {
                        progressBar();
                        $("#algoIntro").empty();
                        $("#algoIntro").append(data["algo_information"]);
                        $("#algoRes").empty();
                        $("#algoRes").append('重连通子图');
                        $("#algoRes").append("<br/>");
                        $("#algoRes").append('结果:');
                        $("#algoRes").append("<br/>");
                        data["Components"].forEach(function (v, k) {
                            $("#algoRes").append('[' + v + ']');
                            $("#algoRes").append(",");
                        });
                        $("#algoRes").append("<br/>");
                        $("#algoRes").append("子图大小映射:");
                        $("#algoRes").append((JSON.stringify(data["ComponentSizes"])));
                    }
                });
            });


            $("#nkit_getWeaklyConnectedComponents").on('click', function () {
                progressBarToZero();
                console.log('nkit_getWeaklyConnectedComponents');
                var dataArray = [];
                for (var j = 0; j < net.edges.length; j++) {
                    dataArray[j] = new Array(4);
                    for (var k = 0; k < 2; k++) {
                        if (k === 0) {
                            dataArray[j][k] = parseInt(net.edges[j].source)
                        } else
                            dataArray[j][k] = parseInt(net.edges[j].target)
                    }
                    dataArray[j][2] = dataArray[j][3] = 1;//边的另外两个属性，暂时搁置
                }
                let num_nodes = net.nodes.length;
                $.ajax({
                    type: "POST",
                    url: "/networkitapi/getWeaklyComponents",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({//发送到服务器的数据
                        data: dataArray,
                        num_nodes: num_nodes
                    }),
                    dataType: "JSON",
                    success: function (data) {
                        progressBar();
                        console.log(data);
                        if (data["isSuccess"] == 1) {
                            $("#algoIntro").empty();
                            $("#algoIntro").append(data["algo_information"]);
                            $("#algoRes").empty();
                            $("#algoRes").append('弱连通子图');
                            $("#algoRes").append("<br/>");
                            $("#algoRes").append('结果:');
                            $("#algoRes").append("<br/>");
                            data["Components"].forEach(function (v, k) {
                                $("#algoRes").append('[' + v + ']');
                                $("#algoRes").append(",");
                            });
                            $("#algoRes").append("<br/>");
                            $("#algoRes").append("子图大小映射:");
                            $("#algoRes").append((JSON.stringify(data["ComponentSizes"])));
                        } else {
                            $("#algoRes").empty();
                            $("#algoRes").append(data["error"]);
                        }

                    }
                });
            });


            $("#nkit_PLM").on('click', function () {
                progressBarToZero();
                $("#role_network").hide();
                $("#network2").show();
                var dataArray = [];
                for (var j = 0; j < net.edges.length; j++) {
                    dataArray[j] = new Array(4);
                    for (var k = 0; k < 2; k++) {
                        if (k === 0) {
                            dataArray[j][k] = parseInt(net.edges[j].source)
                        } else
                            dataArray[j][k] = parseInt(net.edges[j].target)
                    }
                    dataArray[j][2] = dataArray[j][3] = 1;//边的另外两个属性，暂时搁置
                }
                console.log('nkit_PLM');
                let num_nodes = net.nodes.length;
                $.ajax({
                    type: "POST",
                    url: "/networkitapi/parallelLouvain",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({//发送到服务器的数据
                        data: dataArray,
                        num_nodes: num_nodes
                    }),
                    dataType: "JSON",
                    success: function (data) {
                        progressBar();
                        // console.log(data)
                        $("#algoRes").empty();
                        // $("#algoRes").append(data)
                        net = JSON.parse(JSON.stringify(origin_net));
                        var network2 = $('#network2');
                        var cnt = 0;
                        myChart3 = echarts.init(network2.get(0));
                        visulizedCommunity(myChart3, data, net);

                    }
                });
            });


            $("#nkit_PLP").on('click', function () {
                progressBarToZero();
                $("#role_network").hide();
                $("#network2").show();
                var dataArray = [];
                for (var j = 0; j < net.edges.length; j++) {
                    dataArray[j] = new Array(4);
                    for (var k = 0; k < 2; k++) {
                        if (k === 0) {
                            dataArray[j][k] = parseInt(net.edges[j].source)
                        } else
                            dataArray[j][k] = parseInt(net.edges[j].target)
                    }
                    dataArray[j][2] = dataArray[j][3] = 1;//边的另外两个属性，暂时搁置
                }
                let num_nodes = net.nodes.length;
                console.log('nkit_PLP');
                $.ajax({
                    type: "POST",
                    url: "/networkitapi/parallelLabelPropagation",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({//发送到服务器的数据
                        data: dataArray,
                        num_nodes: num_nodes
                    }),
                    dataType: "JSON",
                    success: function (data) {
                        progressBar();
                        // console.log(data)
                        $("#algoRes").empty();
                        // $("#algoRes").append(data)
                        net = JSON.parse(JSON.stringify(origin_net));
                        var network2 = $('#network2');
                        var categories = [];
                        myChart3 = echarts.init(network2.get(0));
                        visulizedCommunity(myChart3, data, net);

                    }
                });
            });

            $("#CommonNeighborsIndex").on('click', function (e) {
                console.log("CommonNeighborsIndex")
                progressBarToZero();
                $("#role_network").hide();
                $("#network2").show();
                var dataArray = [];
                for (var j = 0; j < net.edges.length; j++) {
                    dataArray[j] = new Array(4);
                    for (var k = 0; k < 2; k++) {
                        if (k === 0) {
                            dataArray[j][k] = parseInt(net.edges[j].source)
                        } else
                            dataArray[j][k] = parseInt(net.edges[j].target)
                    }
                    dataArray[j][2] = dataArray[j][3] = 1;//边的另外两个属性，暂时搁置
                }
                let num_nodes = net.nodes.length;
                let startTime = new Date();
                $.ajax({
                    type: "POST",
                    url: "/networkitapi/CommonNeighborsIndex",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({//发送到服务器的数据
                        data: dataArray,
                        num_nodes: num_nodes
                    }),
                    dataType: "JSON",
                    success: function (data, message) {
                        progressBar();
                        net = JSON.parse(JSON.stringify(origin_net));
                        var cnt = 15;
                        //残留一个问题，为什么这里是15，可是图上好像并没有展示15条边
                        // console.log(data)
                        // console.log(data["result"])
                        data = data["result"].slice(0, cnt);  //data是按概率大小降序排列，这里取了前15条边，作为大概率边

                        var network2 = $('#network2');
                        $("#algoRes").empty();
                        $("#algoRes").append(data["description"]);
                        myChart2 = echarts.init(network2.get(0));
                        myChart2.clear();
                        myChart2.showLoading();
                        myChart2.hideLoading();
                        Object.keys(data).forEach(function (v, k) {
                            var link = {
                                source: data[v][0],
                                target: data[v][1]
                            }
                            var wid = data[v][2] > 1 ? data[v][2] : (data[v][2] * 10 + 3); //宽度
                            link.lineStyle = {
                                width: wid,
                                color: '#00fff6'
                            }
                            net.edges.push(link);
                        });
                        option = {
                            tooltip: {},
                            series: [{
                                type: 'graph',
                                layout: 'force',
                                roam: true,
                                force: {
                                    repulsion: 150,
                                    edgeLength: 200,
                                    layoutAnimation: false
                                },
                                edgeSymbol: ['', 'arrow'],
                                data: net.nodes,
                                links: net.edges,
                                label: {
                                    normal: {
                                        show: false,
                                        textStyle: {
                                            fontSize: 10
                                        },
                                    }
                                },
                                itemStyle: {
                                    color: '#FD9133'
                                },
                                edgeLabel: {
                                    show: true,
                                    normal: {
                                        textStyle: {
                                            fontSize: 20
                                        }
                                    }
                                },
                                normal: {
                                    width: 0.3,
                                    curveness: 0.3,
                                    opacity: 0.7
                                }
                            }]
                        };
                        myChart2.setOption(option);
                        Object.keys(data).forEach(function (v, k) {
                            $("#algoRes").append('[' + data[v][0] + ',' + data[v][1] + ',' + data[v][2] + ']');
                            $("#algoRes").append("<br/>");
                        });
                        if (message > 0) {
                            alert("请求已提交！我们会尽快与您取得联系");
                        }
                    },
                    error: function (message) {
                        $("#request-process-patent").html("提交数据失败！");
                    }
                });
                timeCntFn(startTime, new Date());
            });

            //节点中心性指标计算
            $("#nodeAlgo").on('click', function (e) {
                progressBarToZero();
                $("#role_network").hide();
                $("#network2").show();
                var id = e.target.id;
                var dataArray = [];
                var algoArray = ["algo1", "algo2", "algo3", "algo4", "algo5", "algo6", "algo7", "algo8", "algo9"];
                var api = -1;
                for (var i = 0; i < algoArray.length; i++) {
                    if (id === algoArray[i]) {
                        api = i;
                        for (var j = 0; j < net.edges.length; j++) {
                            dataArray[j] = new Array(4);
                            for (var k = 0; k < 2; k++) {
                                if (k === 0) {
                                    dataArray[j][k] = parseInt(net.edges[j].source)
                                } else
                                    dataArray[j][k] = parseInt(net.edges[j].target)
                            }
                            dataArray[j][2] = dataArray[j][3] = 1;
                        }
                        break;
                    }
                }
                api = api + 2;
                $("#algoIntro").empty();
                switch (api) {
                    case 2:
                        $("#algoIntro").append('计算网络中节点的度中心性');
                        break;
                    case 3:
                        $("#algoIntro").append('计算网络中节点的紧密度中心性');
                        break;
                    case 4:
                        $("#algoIntro").append('计算网络中节点的介数中心性');
                        break;
                    case 5:
                        $("#algoIntro").append('计算网络中边的介数中心性');
                        break;
                    case 6:
                        $("#algoIntro").append('计算网络中的流紧密中心性');
                        break;
                    case 7:
                        $("#algoIntro").append('计算网络中的流介数中心性');
                        break;
                    case 8:
                        $("#algoIntro").append('计算网络中的特征向量中心性');
                        break;
                    case 9:
                        $("#algoIntro").append('计算网络中的特征向量中心性');
                        break;
                    case 10:
                        $("#algoIntro").append('计算网络中的加载中心性');
                        break;
                    default:
                        break;
                }
                let startTime = new Date();
                $.ajax({
                        type: "POST",
                        url: "/networkapi/",
                        contentType: "application/json; charset=utf-8",
                        data: JSON.stringify({
                            data: dataArray,
                            api: api
                        }),
                        dataType: "JSON",
                        success: function (data, message) {
                            progressBar();
                            net = JSON.parse(JSON.stringify(origin_net));
                            var cnt = 20;
                            var metric = $('#metric');
                            $("#algoRes").empty();
                            myChart1 = echarts.init(metric.get(0));
                            myChart1.clear();
                            myChart1.showLoading();
                            myChart1.hideLoading();
                            if (api === 5) {
                                net.edges.forEach(link => {
                                    link.lineStyle = {
                                        color: (cnt--) > 0 ? '#00fff6' : 'grey'
                                    };
                                    Object.keys(data).forEach(function (v, k) {
                                        if ((link.source == data[v][0]) && (link.target == data[v][1])) {
                                            var wid = data[v][2] * 10 + 3;
                                            link.lineStyle = {
                                                width: wid,
                                                color: (cnt--) > 0 ? 'green' : 'grey'
                                            }
                                        }
                                    })
                                });
                                option = {
                                    tooltip: {},
                                    series: [{
                                        type: 'graph',
                                        layout: 'force',
                                        roam: true,
                                        force: {
                                            repulsion: 150,
                                            edgeLength: 200,
                                            layoutAnimation: false
                                        },
                                        edgeSymbol: ['', 'arrow'],
                                        data: net.nodes,
                                        links: net.edges,
                                        label: {
                                            normal: {
                                                show: false,
                                                textStyle: {
                                                    fontSize: 10
                                                },
                                            }
                                        },
                                        itemStyle: {
                                            color: '#FD9133'
                                        },
                                        edgeLabel: {
                                            show: true,
                                            normal: {
                                                textStyle: {
                                                    fontSize: 20
                                                }
                                            }
                                        },
                                        normal: {
                                            width: 0.3,
                                            curveness: 0.3,
                                            opacity: 0.7
                                        }
                                    }]
                                };
                                // console.log(JSON.stringify(option))
                                myChart1.setOption(option);
                                Object.keys(data).forEach(function (v, k) {
                                    $("#algoRes").append('[' + data[v][0] + ',' + data[v][1] + ',' + data[v][2] + ']');
                                    $("#algoRes").append("<br/>");
                                });
                            } else {
                                net.nodes.forEach(node => {
                                    if (!isNaN(data[node.name])) {
                                        if (api == 3 || api == 2) {
                                            node.symbolSize = (Math.abs(data[node.name] * 100) + 30) / 3;
                                        } else {
                                            node.symbolSize = Math.abs(data[node.name] * 100) + 30;
                                        }
                                        console.log(node.symbolSize)
                                    }
                                });
                                option = {
                                    tooltip: {},
                                    series: [{
                                        type: 'graph',
                                        layout: 'force',
                                        symbolSize: 5,
                                        roam: true,
                                        force: {
                                            repulsion: 150,
                                            edgeLength: 200,
                                            layoutAnimation: false
                                        },
                                        edgeSymbol: ['', 'arrow'],
                                        data: net.nodes,
                                        links: net.edges,
                                        label: {
                                            normal: {
                                                show: false,
                                                textStyle: {
                                                    fontSize: 10
                                                },
                                            }
                                        },
                                        itemStyle: {
                                            color: '#FD9133'
                                        },
                                        edgeLabel: {
                                            show: true,
                                            normal: {
                                                textStyle: {
                                                    fontSize: 20
                                                }
                                            }
                                        },

                                    }]
                                };
                                // console.log(JSON.stringify(option))
                                myChart1.setOption(option);
                                Object.keys(data).forEach(function (key) {
                                    $("#algoRes").append(key + ':' + data[key]);
                                    $("#algoRes").append("<br/>");
                                });
                            }
                            if (message > 0) {
                                alert("请求已提交！我们会尽快与您取得联系");
                            }
                        },
                        error: function (message) {
                            $("#request-process-patent").html("提交数据失败！");
                        }
                    }
                );
                timeCntFn(startTime, new Date());
            });


            //链接预测
            $("#linkAlgo").on('click', function (e) {
                progressBar();
                $("#role_network").hide();
                $("#network2").show();
                var id = e.target.id;
                var dataArray = [];
                var algoArray = ["algo10", "algo11", "algo12", "algo13"];
                var api = -1;
                for (var i = 0; i < algoArray.length; i++) {
                    if (id === algoArray[i]) {
                        api = i;
                        for (var j = 0; j < net.edges.length; j++) {
                            dataArray[j] = new Array(4);
                            for (var k = 0; k < 2; k++) {
                                if (k === 0) {
                                    dataArray[j][k] = parseInt(net.edges[j].source)
                                } else
                                    dataArray[j][k] = parseInt(net.edges[j].target)
                            }
                            dataArray[j][2] = dataArray[j][3] = 1;
                        }
                        break;
                    }
                }
                if (i === algoArray.length) {
                    return false;//所点击的算法不在algoArray内，就终止监听
                }

                api = api + 11;
                $("#algoIntro").empty();
                switch (api) {
                    case 11:
                        $("#algoIntro").append('计算网络中未连边的节点之间有边的概率');
                        break;
                    case 12:
                        $("#algoIntro").append('对网络中的节点之间有无边进行预测，即概率的计算');
                        break;
                    case 13:
                        $("#algoIntro").append('通过 Adamic-Adar index算法进行链接预测');
                        break;
                    case 14:
                        $("#algoIntro").append('通过偏好连接方法对节点进行评分');
                        break;
                    default:
                        break;
                }
                let startTime = new Date();
                $.ajax({
                    type: "POST",
                    url: "/networkapi/",
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({
                        data: dataArray,
                        api: api
                    }),
                    dataType: "JSON",
                    success: function (data, message) {
                        progressBar();
                        net = JSON.parse(JSON.stringify(origin_net));
                        var cnt = 15;
                        data = data.slice(0, cnt);  //data是按概率大小降序排列，这里取了前15条边，作为大概率边
                        var linkPrediction = $('#linkPrediction');
                        $("#algoRes").empty();
                        myChart2 = echarts.init(linkPrediction.get(0));
                        myChart2.clear();
                        myChart2.showLoading();
                        myChart2.hideLoading();
                        Object.keys(data).forEach(function (v, k) {
                            var link = {
                                source: data[v][0],
                                target: data[v][1]
                            }
                            var wid = data[v][2] > 1 ? data[v][2] : (data[v][2] * 10 + 3);
                            link.lineStyle = {
                                width: wid,
                                color: '#00fff6'
                            }
                            net.edges.push(link);
                        });
                        option = {
                            tooltip: {},
                            series: [{
                                type: 'graph',
                                layout: 'force',
                                roam: true,
                                force: {
                                    repulsion: 150,
                                    edgeLength: 200,
                                    layoutAnimation: false
                                },
                                edgeSymbol: ['', 'arrow'],
                                data: net.nodes,
                                links: net.edges,
                                label: {
                                    normal: {
                                        show: false,
                                        textStyle: {
                                            fontSize: 10
                                        },
                                    }
                                },
                                itemStyle: {
                                    color: '#FD9133'
                                },
                                edgeLabel: {
                                    show: true,
                                    normal: {
                                        textStyle: {
                                            fontSize: 20
                                        }
                                    }
                                },
                                normal: {
                                    width: 0.3,
                                    curveness: 0.3,
                                    opacity: 0.7
                                }
                            }]
                        };
                        myChart2.setOption(option);
                        Object.keys(data).forEach(function (v, k) {
                            $("#algoRes").append('[' + data[v][0] + ',' + data[v][1] + ',' + data[v][2] + ']');
                            $("#algoRes").append("<br/>");
                        });
                        if (message > 0) {
                            alert("请求已提交！我们会尽快与您取得联系");
                        }
                    },
                    error: function (message) {
                        $("#request-process-patent").html("提交数据失败！");
                    }
                });
                timeCntFn(startTime, new Date());
            });

            //社团检测
            $("#communityAlgo").on('click', function (e) {
                progressBarToZero();
                $("#role_network").hide();
                $("#network2").show();
                var id = e.target.id;
                var dataArray = [];
                var algoArray = ["algo14", "algo15", "algo16"];
                var api = -1;
                for (var i = 0; i < algoArray.length; i++) {
                    if (id === algoArray[i]) {
                        api = i;
                        for (var j = 0; j < net.edges.length; j++) {
                            dataArray[j] = new Array(4);
                            for (var k = 0; k < 2; k++) {
                                if (k === 0) {
                                    dataArray[j][k] = parseInt(net.edges[j].source)
                                } else
                                    dataArray[j][k] = parseInt(net.edges[j].target)
                            }
                            dataArray[j][2] = dataArray[j][3] = 1;
                        }
                        break;
                    }
                }
                api = api + 15;
                $("#algoIntro").empty();
                switch (api) {
                    case 15:
                        $("#algoIntro").append('利用异步的fluid社团检测方法对社团进行划分，该算法需要提前指定社团个数');
                        break;
                    case 16:
                        $("#algoIntro").append('利用异步标签传播算法对网络进行社团划分');
                        break;
                    case 17:
                        $("#algoIntro").append('标签传播算法是基于图的半监督学习方法，基本思路是从已标记的节点的标签信息来预测未标记的节点的标签信息，利用样本间的关系，建立完全图模型。');
                        break;
                    default:
                        break;
                }
                var postData = (api === 15) ? JSON.stringify({
                    data: dataArray,
                    para: 2,
                    api: api
                }) : JSON.stringify({data: dataArray, api: api});
                let startTime = new Date();
                $.ajax({
                    type: "POST",
                    url: "/networkapi/",
                    contentType: "application/json; charset=utf-8",
                    data: postData,
                    dataType: "JSON",
                    success: function (data, message) {
                        progressBar();
                        net = JSON.parse(JSON.stringify(origin_net));
                        var communityDetect = $('#communityDetect');
                        $("#algoRes").empty();
                        var cnt = 0;
                        var categories = [];
                        myChart3 = echarts.init(communityDetect.get(0));
                        myChart3.clear();
                        myChart3.showLoading();
                        myChart3.hideLoading();
                        for (let [key, value] of Object.entries(data)) {
                            cnt++;
                            var community = Array.from(value);
                            community.forEach(function (value) {
                                net.nodes.forEach(node => {
                                    if (value == node.name) {
                                        node.category = parseInt(key);
                                    }
                                })
                            })
                        }
                        var legend = [];
                        for (var i = 0; i < cnt; i++) {
                            categories[i] = {
                                name: '社团' + (i + 1)
                            };
                            legend[i] = {
                                name: '社团' + (i + 1)
                            };
                        }
                        option = {
                            tooltip: {},
                            legend: {
                                data: legend,
                                textStyle: {
                                    color: 'white'
                                }
                            },
                            series: [{
                                type: 'graph',
                                layout: 'force',
                                roam: true,
                                force: {
                                    repulsion: 150,
                                    edgeLength: 200,
                                    layoutAnimation: false
                                },
                                edgeSymbol: ['', 'arrow'],
                                categories: categories,
                                data: net.nodes,
                                links: net.edges,
                                label: {
                                    normal: {
                                        show: false,
                                        textStyle: {
                                            fontSize: 10
                                        },
                                    }
                                },
                                edgeLabel: {
                                    show: true,
                                    normal: {
                                        textStyle: {
                                            fontSize: 20
                                        }
                                    }
                                },
                                normal: {
                                    width: 0.3,
                                    curveness: 0.3,
                                    opacity: 0.7
                                }
                            }]
                        };
                        myChart3.setOption(option);
                        Object.keys(data).forEach(function (v, k) {
                            $("#algoRes").append("[");
                            for (var i = 0; i < data[v].length - 1; i++) {
                                $("#algoRes").append(data[v][i] + ',');
                            }
                            $("#algoRes").append(data[v][data[v].length - 1] + ']');
                            $("#algoRes").append("<br/>");
                        });
                        if (message > 0) {
                            alert("请求已提交！我们会尽快与您取得联系");
                        }
                    },
                    error: function (message) {
                        $("#request-process-patent").html("提交数据失败！");
                    }
                });
                timeCntFn(startTime, new Date());
            });

            //角色
            $("#role").on('click', function (e) {
                progressBarToZero();
                var args = {};
                var id = e.target.id;
                $("#network2").hide();
                $("#role_network").show();
                $.ajax({
                    url: '/networkapi/args',
                    type: 'get',
                    data: {
                        'method': id
                    },
                    async: true,
                    success: function (data) {
                        $('#algoIntro').empty();
                        for (var key in data) {
                            $('#algoIntro').append(
                                $("<div class='col-md-3'>" +
                                    "<div class='form-group'>" +
                                    "<label for='key'>" + key +
                                    "</label>" +
                                    "<input type='text' class='form-control' name='role' id='" + key +
                                    "' value='" + data[key] +
                                    "'>" +
                                    "</div>" +
                                    "</div>")
                            );
                        }
                        $('#algoIntro').append($("<div class='col-md-3'>" +
                            "<button class='btn btn-primary' id='exec'>运行</button>" +
                            "</div>"));
                        $("#exec").on('click', function (e) {
                            $("#algoRes").empty();
                            task_id = new Date().getTime();
                            $("input[name=role]").each(function () {
                                args[$(this).attr('id')] = $(this).val();
                            });
                            $.ajax({
                                url: '/networkapi/role',
                                type: 'post',
                                data: JSON.stringify({
                                    data: edges,
                                    task_id: task_id
                                }),
                                success: function (data) {
                                    progressBarToZero();
                                    var post_data = {
                                        method: id,
                                        args: args,
                                        task_id: task_id
                                    };
                                    if (labels.length > 0) {
                                        post_data['label'] = labels;
                                    }
                                    socket.emit('status', post_data);
                                }
                            });
                        });
                    }
                });
            })
            // 下载按钮
            $("#Download").on('click', function () {
                console.log("Download");
                var result_str = $("#algoRes").html();
                result_str = result_str.replace(/<br>/g, '\n')
                console.log(result_str)
                saveShareContent(result_str, "result.txt")

            })
        }
    }
    ;
    var start = new apiFn();
    start.Init()
})
;

function saveShareContent(content, fileName) {
    let downLink = document.createElement('a')
    downLink.download = fileName
    //字符内容转换为blod地址
    let blob = new Blob([content])
    downLink.href = URL.createObjectURL(blob)
    // 链接插入到页面
    document.body.appendChild(downLink)
    downLink.click()
    // 移除下载链接
    document.body.removeChild(downLink)
}

function timeCntFn(startTime, endTime) {
    let res = Math.floor(Math.floor(endTime - startTime));
    console.log(res + 'ms');
    $("#time").empty();
    $("#time").append(res + 'ms');
}

function visulizedCommunity(myChart3, data, net) {

    myChart3.clear();
    myChart3.showLoading();
    myChart3.hideLoading();
    console.log(data['communities'])
    var cnt = 0;
    for (let [key, value] of Object.entries(data['communities'])) {
        //key:communityid,value:list of nodes
        var community = Array.from(value);
        if (community.length > 5) {//只有节点数大于5的社区，才会是社区数量cnt加12
            cnt++;
        }
        ;

        community.forEach(function (value) {
            net.nodes.forEach(node => {
                if (value == node.name) {
                    node.category = parseInt(key); //节点所属社区

                }
            })
        })
    }
    var categories = [];
    var legend = [];
    for (var i = 0; i < cnt; i++) {
        categories[i] = {
            name: '社团' + (i + 1)
        };
        legend[i] = {
            name: '社团' + (i + 1)
        };
    }

    option = {
        tooltip: {},
        // legend: {
        //     data: legend,
        //     textStyle: {
        //         color: 'white'
        //     }
        // },
        series: [{
            type: 'graph',
            layout: 'force',
            roam: true,
            force: {
                repulsion: 150,
                edgeLength: 200,
                layoutAnimation: false
            },
            edgeSymbol: ['', 'arrow'],
            categories: categories,
            data: net.nodes,
            links: net.edges,
            label: {
                normal: {
                    show: false,
                    textStyle: {
                        fontSize: 10
                    },
                }
            },
            edgeLabel: {
                show: true,
                normal: {
                    textStyle: {
                        fontSize: 20
                    }
                }
            },
            normal: {
                width: 0.3,
                curveness: 0.3,
                opacity: 0.7
            }
        }]
    };
    myChart3.setOption(option);
    $("#algoRes").append(data["OtherInformation"]);
    $("#algoRes").append("<br/>");
    $("#algoRes").append("result:");
    $("#algoRes").append((JSON.stringify(data["communities"])));
}


function progressBarToZero() {
    return "not implemented"
    var myDiv = document.getElementById("myDiv");
    myDiv.style.width = 0 + "%";
    myDiv.innerText = 0 + "%";
}

function progressBar() {
    return "not implemented"
    var myDiv = document.getElementById("myDiv");
    myDiv.style.width = 100 + "%";
    myDiv.innerText = 100 + "%";
}